'use strict';

module.exports = () => {
  return async function auth(ctx, next) {
    // 从配置文件获取需要跳过认证的路由
    const ignoreRoutes = ctx.app.config.auth?.ignore || [];

    const shouldSkip = ignoreRoutes.some(route => {
      if (route === '/') {
        return ctx.path === '/';
      }
      return ctx.path === route || ctx.path.startsWith(route);
    });

    if (shouldSkip) {
      await next();
      return;
    }

    // 获取token
    const token = ctx.get('Authorization')?.replace('Bearer ', '') ||
                  ctx.query.token ||
                  ctx.request.body?.token;
                  console.log('token',token)
    if (!token) {
      ctx.throw(401, '未提供认证令牌');
    }
    
    // 验证token
    const decoded = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

    // 获取用户信息
    const userModel = await ctx.service.user.findById(decoded.id);
    if (!userModel) {
      ctx.throw(401, '用户不存在');
    }

    if (userModel.status !== 'active') {
      ctx.throw(401, '用户已被禁用');
    }

    // 将用户信息转换为纯对象并存储到ctx.state中
    const user = userModel.toJSON ? userModel.toJSON() : userModel.dataValues;
    ctx.state.user = user;

    await next();
  };
};
